<!-- src/App.vue -->
<template>
  <view class="home-container">
    <!-- 顶部自定义栏：地址 + 推荐/常点 -->
    <view class="header-section padding-lr padding-tb-sm">
      <view class="flex align-center">
        <view class="address-section" @click="goToAddressPage">
          <text class="cuIcon-locationfill text-orange"></text>
          <text class="text-bold margin-left-xs">{{ currentAddress }}</text>
          <text class="cuIcon-right"></text>
        </view>
      </view>
    </view>

    <!-- 搜索框 -->
    <view class="cu-bar search bg-white">
      <view class="search-form round">
        <text class="cuIcon-search"></text>
        <input
          type="text"
          placeholder="搜索商家或商品"
          v-model="searchText"
          @confirm="performSearch"
        />
      </view>
      <view class="action">
        <button
          class="cu-btn bg-gradual-green shadow-blur round"
          @click="performSearch"
        >
          搜索
        </button>
      </view>
    </view>

    <!-- 横向分类选择 -->
    <view class="bg-white padding-bottom-sm">
      <scroll-view scroll-x class="nav">
        <view class="flex text-center">
          <view
            class="cu-item"
            style="min-width: 160rpx; line-height: 1"
            v-for="(item, index) in categories"
            :key="index"
            @tap="selectCategory(item.typeName, item.id)"
          >
            <view
              :class="[
                'cuIcon-' + item.typeIcon,
                activeCategory === item.typeName
                  ? 'text-' + item.color
                  : 'text-gray',
              ]"
              style="font-size: 52rpx"
            ></view>
            <view
              class="text-sm"
              :class="
                activeCategory === item.typeName
                  ? 'text-black text-bold'
                  : 'text-gray'
              "
              >{{ item.typeName }}</view
            >
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 快捷标签
		<view class="padding-lr padding-bottom-sm">
			<scroll-view scroll-x class="nav">
				<view class="flex">
					<view class="cu-tag round margin-right-xs" v-for="(tag, index) in tags" :key="index">{{ tag }}</view>
				</view>
			</scroll-view>
		</view> -->

    <!-- 商家列表标题 -->
    <view class="cu-bar bg-white solid-bottom">
      <view class="action">
        <text class="cuIcon-titles text-orange"></text>
        <text class="text-bold">附近商家</text>
      </view>
    </view>

    <!-- 商家列表 -->
    <view class="merchant-list">
      <view
        class="card-wrapper"
        v-for="merchant in merchants"
        :key="merchant.id"
      >
        <MerchantCard :merchant="merchant" />
        <!-- 当 businessStatus 为 0 时显示遮罩层 -->
        <view v-if="merchant.businessStatus === 0" class="closed-mask">
          <text>已打烊</text>
        </view>
      </view>
      
    </view>
    <GlobalAIFloat />
  </view>
</template>

<script setup>
import MerchantCard from "@/components/MerchantCard.vue";
import GlobalAIFloat from "@/components/GlobalAIFloat.vue";
import { onMounted, ref } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { get } from "@/utils/request.js";

const merchants = ref([]);
const loading = ref(true);
const activeTab = ref("recommend");
const activeCategory = ref("美食");
const searchText = ref("");
// const tags = ref(['学生特价', '天天爆红包', '减配送费', '无门槛红包']);
const categories = ref([]);

const currentAddress = ref("厦门工学院");

const goToAddressPage = () => {
  uni.navigateTo({
    url: "/pages/address/index",
  });
};

const performSearch = () => {
  const keyword = searchText.value.trim();
  if (!keyword) {
    uni.showToast({
      title: "请输入搜索内容",
      icon: "none",
    });
    return;
  }
  uni.navigateTo({
    url: `/pages/search/index?keyword=${encodeURIComponent(keyword)}`,
  });
};

onShow(() => {
	const selectedAddress = uni.getStorageSync('selectedAddress');
	if (selectedAddress) {
		currentAddress.value = selectedAddress;
	}
});

const selectCategory = (typeName, typeId) => {
  activeCategory.value = typeId;
  console.log(typeId);
  uni.showToast({
    title: `已切换到 ${typeName} 分类`,
    icon: "none",
  });
  // 在实际应用中，这里会触发筛选商家列表的逻辑
  fetchmerchant();
};

const recentMerchant = async () => {
  try {
    const selectedAddress = uni.getStorageSync("selectedAddress");
    const latitude = uni.getStorageSync("latitude");
    const longitude = uni.getStorageSync("longitude");
    console.log(latitude,longitude)
    const res = await get(
      `/merchant/getMerInfoByLocation?selectedAddress=${selectedAddress}&latitude=${latitude}&longitude=${longitude}`
    );
    console.log("最近店铺数据", res);
    const mertchantList = [];
    res.data.data.forEach((item) => {
      const merchant = {
        id: item.merId,
        name: item.merName,
        rating: item.merScore,
        monthlySales: 100,
        // 距离处理
        distance:
          item.distance >= 1000
            ? (item.distance / 1000).toFixed(1) + "公里"
            : item.distance + "米",
        tags: ["会员红包膨胀14元起", "爆12元"],
        businessStatus: item.businessStatus,
        banner: item.icon,
        products: [],
      };
      mertchantList.push(merchant);
    });
    merchants.value = mertchantList;
    uni.setStorageSync("merchants_data", mertchantList); // 将商家列表存入缓存
    loading.value = false;
  } catch (error) {
    console.error("请求失败", error);
    loading.value = false;
  }
};

const fetchmerchant = async () => {
	try {
		loading.value = true;
		const res = await get(`/merchant/getMerchantInfo?typeId=${activeCategory.value}`);
		console.log('店铺数据', res);
    const mertchantList = [];
    res.data.msg.forEach((item) => {
     const merchant = {
			id: item.merId,
			name: item.merName,
			rating: item.merScore,
			monthlySales: 100,
			distance: '2.4km',
			tags: ['会员红包膨胀14元起', '爆12元'],
			businessStatus : item.businessStatus,
			banner: item.icon,
			products: [],
		}
    	mertchantList.push(merchant);
    })
	
		merchants.value = mertchantList;
		uni.setStorageSync('merchants_data', mertchantList); // 将商家列表存入缓存
		
		loading.value = false;
	} catch (error) {
		console.error('请求失败', error);
		loading.value = false;
	}
};

const fetchmerchantType = async () => {
  try {
    const res = await get("/merchant/getMerchantType");
    console.log("店铺分类数据", res);
    categories.value = res.data.msg.map((item) => ({
      id: item.typeId,
      typeName: item.typeName,
      typeIcon: item.typeIcon,
      color: item.color,
    }));
  } catch (error) {
    console.error("请求失败", error);
  }
};

onMounted(async () => {
  await Promise.allSettled([fetchmerchantType()]);
});
</script>

<style scoped>
.home-container {
  background-color: #f8f8f8;
  min-height: 100vh;
}
.header-section {
  background-color: #ffffff;
}
.address-section {
  font-size: 32rpx;
  color: #333;
}
.merchant-list {
  padding-bottom: 60px;
}
.home-container {
  background-color: #f8f8f8;
  min-height: 100vh;
}
/* ... 其他样式保持不变 ... */

/* 新增：卡片包裹容器 */
.card-wrapper {
  position: relative;
}

/* 遮罩层样式 */
.closed-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 36rpx;
  font-weight: bold;
  z-index: 10;
  border-radius: 16rpx; /* 匹配卡片的圆角 */
}
</style>
